package org.cxy.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.cxy.entity.TargetTable;
import org.cxy.mapper.TargetTableMapper;
import org.cxy.model.IdRange;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class TargetTableService extends ServiceImpl<TargetTableMapper, TargetTable> {
    
    /**
     * 查询主键ID范围
     */
    public IdRange getIdRange() {
        return baseMapper.selectIdRange();
    }
    
    /**
     * 查询分段数据
     */
    public List<TargetTable> getSegmentData(Long startId, Long endId) {
        return baseMapper.selectBySegment(startId, endId);
    }
    
    /**
     * 批量更新状态为已处理
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateToProcessed(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return true;
        }
        
        try {
            // 使用 MyBatis-Plus 的更新方式
            return this.lambdaUpdate()
                    .set(TargetTable::getStatus, "PROCESSED")
                    .set(TargetTable::getProcessTime, java.time.LocalDateTime.now())
                    .in(TargetTable::getId, ids)
                    .update();
        } catch (Exception e) {
            log.error("批量更新状态失败", e);
            throw e;
        }
    }
    
    /**
     * 更新单条记录状态
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRecordStatus(Long id, String status, String errorMsg) {
        try {
            TargetTable entity = new TargetTable();
            entity.setId(id);
            entity.setStatus(status);
            
            if ("FAILED".equals(status)) {
                entity.setErrorMsg(errorMsg);
            } else if ("PROCESSED".equals(status)) {
                entity.setProcessTime(java.time.LocalDateTime.now());
            }
            
            return this.updateById(entity);
        } catch (Exception e) {
            log.error("更新记录状态失败: {}", id, e);
            return false;
        }
    }
}